﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using TmU220PrintHelperV2d0.ControlUi;
using TmU220PrintHelperV2d0.Entity;
using TmU220PrintHelperV2d0.Service;
using TmU220PrintHelperV2d0.Singleton;
using unvell.ReoGrid;
using unvell.ReoGrid.CellTypes;
using ZhangLogSysV1d0;

namespace PrinterControl
{
    public partial class FormPrintTempletControl : Form
    {
        public FormPrintTempletControl()
        {
            InitializeComponent();
            this.Text = "創域餐飲管理系統-打印模板管理V0.9-2019-11-16";
            PrintTempletRowDisplayList = new List<PrintTempletRowDisplay>();
            PrintTempletElementEditorList = new List<PrintTempletElementEditor>();
            PrintTempletRow = new PrintTempletRowV2d0();
            CurrRowIndex = 0;
            string currDir = System.IO.Directory.GetCurrentDirectory();
            TempletSetXmlFilename = currDir + @"\parameter\PrintTempletSet.xml";
            //从本地文件得到打印模板集
            if(File.Exists(TempletSetXmlFilename))
            {
                PrintTempletSet = PrintTempletSetSingletonV2d0.Instance.GetPrintTempletSet();
            } 
            else
            {
                //本地没有模板文件,从远程下载,保存到本地
                PrintTempletSet = DownloadPrintTempletSet();
                HotchPotchV2d0.SaveToXmFile<PrintTempletSetV2d0>(PrintTempletSet, TempletSetXmlFilename);
            }

            //初始化模板名称下拉框
            InitComboBoxTempletName();
            //初始化模板
            InitPanel();
        }
        /// <summary>
        /// 初始化已有模板名称下拉框
        /// </summary>
        private void InitComboBoxTempletName()
        {
            try
            {
                // var templetSet = PrintTempletSetSingletonV2d0.Instance.GetPrintTempletSet();
                //templetSet=
                //
                //List<string> nameList = templetSet.PrintTempletList.Select(x => x.TempletName).ToList();
                List<string> nameList = PrintTempletSet.PrintTempletList.Select(x => x.TempletName).ToList();
                comboBoxTempletName.Items.Clear();
                comboBoxTempletName.Items.AddRange(nameList.ToArray());
                if (nameList.Count > 0)
                {
                    comboBoxTempletName.Text = PrintTempletSet.PrintTempletList[0].TempletName;
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 模板行显示控件的选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTempletRow"></param>
        public void ProcPanelSelectedEvent(object sender, PrintTempletRowV2d0 printTempletRow)
        {
            try
            {
                CurrRowIndex = printTempletRow.RowIndex;
                buttonAddElement.Enabled = true;
                buttonDeleteElement.Enabled = false;
                PrintTempletRow = printTempletRow;
                if (PrintTempletRow.TempletElementList.Count < 3) buttonAddElement.Enabled = true;
                else buttonAddElement.Enabled = false;
                FillPrintTempletRowToPanelElement(printTempletRow);
                foreach (var item in PrintTempletRowDisplayList)
                {
                    item.IsSelected = false;
                    item.Refresh();
                }
                var itemFinded = PrintTempletRowDisplayList.FirstOrDefault(x => x.Index == printTempletRow.RowIndex);
                if (itemFinded != null)
                {
                    itemFinded.IsSelected = true;
                    itemFinded.Refresh();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 处理PrintTempletElementEditor控件的数据修改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        public void ProcPrintTempletElementEditdorDataChangedEvent(object sender, int rowIndex)
        {
            try
            {
                buttonDeleteElement.Enabled = true;
                PrintTempletElementEditor currElementEditor = (sender as PrintTempletElementEditor);
                foreach (var item in PrintTempletElementEditorList)
                {
                    item.IsSelected = false;
                    if (currElementEditor.radioButtonTextMode.Checked) item.EnterTextMode();                    
                    else item.EnterImageMode();
                    if (currElementEditor.radioButtonBlack.Checked)
                    {
                        item.radioButtonBlack.Checked = true;
                        item.radioButtonRed.Checked = false;
                    }
                    else
                    {
                        item.radioButtonBlack.Checked = false;
                        item.radioButtonRed.Checked = true;
                    }
                    //根据编辑框状态，更新对应的打印模板元素类
                    item.SetPrintTempletElementByEditBox();
                    item.Refresh();
                }
                currElementEditor.IsSelected = true;
                currElementEditor.Refresh();
                var rowDisplay = PrintTempletRowDisplayList.FirstOrDefault(x => x.Index == rowIndex);
                if (rowDisplay != null) rowDisplay.Refresh();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 当前选中模板行的行序号
        /// </summary>
        public int CurrRowIndex { get; set; }
        /// <summary>
        /// 当前打印模板集
        /// </summary>
        public PrintTempletSetV2d0 PrintTempletSet { get; set; }
        /// <summary>
        /// 打印模板信息
        /// </summary>
        private PrintTempletV2d0 PrintTemplet { get; set; }
        /// <summary>
        /// 模板行
        /// </summary>
        private PrintTempletRowV2d0 PrintTempletRow { get; set; }
        /// <summary>
        /// 模板行显示控件列表
        /// </summary>
        private List<PrintTempletRowDisplay> PrintTempletRowDisplayList { get; set; }
        /// <summary>
        /// 模板行元素的编辑控件列表
        /// </summary>
        private List<PrintTempletElementEditor> PrintTempletElementEditorList { get; set; }
        /// <summary>
        /// 打印模板集文件的文件名
        /// </summary>
        public string TempletSetXmlFilename { get; set; }


        private void FormPrintTempletControl_Load(object sender, EventArgs e)
        {
            //UpdatePanelHeight();
        }
        /// <summary>
        /// 填充模板行数据到模板行元素面板中
        /// </summary>
        /// <param name="printTempletRow"></param>
        public void FillPrintTempletRowToPanelElement(PrintTempletRowV2d0 printTempletRow)
        {
            try
            {
                //取消当前元素编辑控件列表中控件的事件订阅
                foreach (var item in PrintTempletElementEditorList) item.DataChangedEvent -= ProcPrintTempletElementEditdorDataChangedEvent;
                //得到元素编辑控件列表
                PrintTempletElementEditorList = GetPrintTempletElementEditorList(printTempletRow);
                tableLayoutPanelElement.Controls.Clear();
                tableLayoutPanelElement.RowStyles.Clear();
                tableLayoutPanelElement.ColumnCount = 1;
                tableLayoutPanelElement.RowCount = PrintTempletElementEditorList.Count;
                for (int i = 0; i < PrintTempletElementEditorList.Count; i++)
                {
                    tableLayoutPanelElement.Controls.Add(PrintTempletElementEditorList[i], 0, i);
                    tableLayoutPanelElement.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 100));
                }
                tableLayoutPanelElement.Refresh();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 根据模板行对象生成对应的模板行元素编辑组件，用于填充到tabLayoutPanel中
        /// </summary>
        /// <param name="printTempletRow"></param>
        /// <returns></returns>
        public List<PrintTempletElementEditor> GetPrintTempletElementEditorList(PrintTempletRowV2d0 printTempletRow)
        {
            List<PrintTempletElementEditor> printTempletElementEditorList = new List<PrintTempletElementEditor>();
            try
            {
                foreach (var item in printTempletRow.TempletElementList)
                {
                    //PrintTempletElementEditor printTempletEditor = new PrintTempletElementEditor(item, printTempletRow.AreaType, printTempletRow.RowIndex);
                    PrintTempletElementEditor printTempletEditor = new PrintTempletElementEditor(item, printTempletRow.AreaType, printTempletRow.RowIndex,typeof(rms_order_print_main),typeof(rms_order_print_detail));
                    printTempletEditor.DataChangedEvent -= ProcPrintTempletElementEditdorDataChangedEvent;
                    printTempletEditor.DataChangedEvent += ProcPrintTempletElementEditdorDataChangedEvent;
                    printTempletElementEditorList.Add(printTempletEditor);
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return printTempletElementEditorList;
        }


        /// <summary>
        /// 保存按钮，将数据保存为配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            SavePrintTempletToFile();
        }
        /// <summary>
        /// 保存打印模板到文件
        /// </summary>
        private void SavePrintTempletToFile()
        {
            try
            {
                string templetName = comboBoxTempletName.Text;
                //var printTemplete = PrintTempletSetSingletonV2d0.Instance.GetPrintTemplet(templetName);
                var printTemplete =  PrintTempletSet.PrintTempletList.FirstOrDefault(x=>x.TempletName==templetName);
                bool isEdit = false;//编辑模板或者新增模板
;
                if (printTemplete == null)
                {
                    //如果无同名配置 直接保存
                    isEdit = false;
                    SetTempleteNameAndSaveToFile(templetName,isEdit);
                }
                else
                {
                    isEdit = true;
                    //如果有同名配置 提示后保存
                    if (MessageBox.Show("是否覆盖当前模板?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                            System.Windows.Forms.MessageBoxIcon.Warning)
                    == System.Windows.Forms.DialogResult.Yes)
                    {
                        SetTempleteNameAndSaveToFile(templetName,isEdit);
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 将编辑框内容赋值给打印模板类，设置其名称，并保存到配置文件中
        /// </summary>
        /// <param name="templetName">模板名称</param>
        private void SetTempleteNameAndSaveToFile(string templetName,bool isEdit)
        {
            try
            {
                // 给模板行的元素添加序号
                foreach(var row in PrintTemplet.PrintTempletRowList)
                {
                    foreach(var item in row.TempletElementList)
                    {
                        int index = row.TempletElementList.IndexOf(item); //index 为索引值
                        item.ElementIndex = index;
                    }
                }
                //---
                PrintTempletV2d0 newPrintTemplet = HotchPotchV2d0.Clone<PrintTempletV2d0>(PrintTemplet);
                //如果是新增就需要给模板一个新的GUID
                if (!isEdit) newPrintTemplet.TempletGuid = Guid.NewGuid();
                newPrintTemplet.TempletName = templetName;
                //更新模板项的打印模式属性
                foreach(var templetRow in newPrintTemplet.PrintTempletRowList)
                {
                    templetRow.PrintMode = templetRow.TempletElementList[0].PrintMode;
                }
                //var printTempletSet = PrintTempletSetSingletonV2d0.Instance.GetPrintTempletSet();
                var printTempletSet = PrintTempletSet;
                //删除同名模板，再进行添加
                printTempletSet.PrintTempletList.RemoveAll(x => x.TempletName == templetName);
                printTempletSet.PrintTempletList.Add(newPrintTemplet);
                string currDir = System.IO.Directory.GetCurrentDirectory();
                string filename = currDir + @"\parameter\printTempletSet.xml";
                PrintTempletSetV2d0.SaveToFile(printTempletSet, filename);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        public CellPosition GetColumnRow(Worksheet currWorkSheet,Point currPoint)
        {
            CellPosition resultPoint = new CellPosition(0, 0);
            //currWorkSheet.
            int headerWidth = currWorkSheet.RowHeaderWidth;
            int colWidthSum = 0;
            for (int i = 0; i < currWorkSheet.Columns; i++)
            {
                colWidthSum += currWorkSheet.GetColumnWidth(i);
                if (currPoint.X < (colWidthSum + headerWidth))
                {
                    resultPoint.Col = i;
                    break;
                }
            }
            int lastColumnLeft= (int)currWorkSheet.GetCellPhysicsPosition(0, 2).X;
            if (currPoint.X > lastColumnLeft + headerWidth) resultPoint.Col = 2;
            int headerHeight = 26;

            int rowHeightSum = 0;
            for (int j = 0; j < currWorkSheet.Rows; j++)
            {
                rowHeightSum+= currWorkSheet.GetRowHeight(j);
                if (currPoint.Y < (rowHeightSum + headerHeight))
                {
                    resultPoint.Row = j ;
                    break;
                }
            }
            return resultPoint;
        }



        /// <summary>
        /// 初始化面板
        /// </summary>
        private void InitPanel()
        {
            try
            {
                string templetName = comboBoxTempletName.Text;
                //PrintTempletV2d0 tmpPrintTemplet= PrintTempletSetSingletonV2d0.Instance.GetPrintTemplet(templetName);
                PrintTempletV2d0 tmpPrintTemplet = PrintTempletSet.PrintTempletList.FirstOrDefault(x => x.TempletName == templetName);
                PrintTemplet = HotchPotchV2d0.Clone<PrintTempletV2d0>(tmpPrintTemplet);
                if (PrintTemplet != null)
                {
                    //取消模板行显示控件的事件订阅
                    foreach (var item in PrintTempletRowDisplayList) item.PanelSelectedEvent -= ProcPanelSelectedEvent;
                    PrintTempletRowDisplayList = GetTempletItemDisplayList(PrintTemplet);
                    FillTableLayoutPanel(PrintTempletRowDisplayList);
                    AdjustTableLayoutPanelHeight(PrintTempletRowDisplayList);
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        
        /// <summary>
        /// 测试用数据
        /// </summary>
        /// <returns></returns>
        public PrintTempletV2d0 GetTestPrintTempletData()
        {

            PrintTempletV2d0 printTemplet = new PrintTempletV2d0();
            PrintTempletRowV2d0 templetRow = new PrintTempletRowV2d0();
            PrintTempletElementV2d0 templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.RowIndex = 0;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.RowIndex = 1;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.RowIndex = 2;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.RowIndex = 3;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.RowIndex = 4;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.AreaType = AreaTypeV2d0.Detail;
            templetRow.RowIndex = 5;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.AreaType = AreaTypeV2d0.Footer;
            templetRow.RowIndex = 6;
            printTemplet.PrintTempletRowList.Add(templetRow);

            templetRow = new PrintTempletRowV2d0();
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Left";
            templetElement.FontSize = 10;
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.FontSize = 20;
            templetElement.HorizontalAlign = "Center";
            templetElement.FontColor = "Red";
            templetRow.TempletElementList.Add(templetElement);
            templetElement = new PrintTempletElementV2d0();
            templetElement.HorizontalAlign = "Right";
            templetElement.FontSize = 12;
            templetRow.TempletElementList.Add(templetElement);
            templetRow.AreaType = AreaTypeV2d0.Footer;
            templetRow.RowIndex = 7;
            printTemplet.PrintTempletRowList.Add(templetRow);

            return printTemplet;
        }
        

        /// <summary>
        /// 根据点坐标，得到该点的行列序号
        /// </summary>
        /// <param name="mousePostion"></param>
        /// <param name="panel"></param>
        /// <returns></returns>
        private Point GetRowColumnIndexOfTableLayoutPanel(Point mousePostion, TableLayoutPanel panel)
        {
            Point rowColumnIndex = new Point(0,0);
            int mouseX = mousePostion.X;
            int mouseY = mousePostion.Y;
            //计算行序号
            int heightSum = 0;
            for (int i = 0; i < panel.RowCount; i++)
            {
                float currRowHeight =
                    panel.RowStyles[i].SizeType == SizeType.Percent ? panel.Height *0.01F* panel.RowStyles[i].Height : panel.RowStyles[i].Height;
                if (i < panel.RowCount - 1) heightSum += (int)currRowHeight;
                else if (i == panel.RowCount - 1) heightSum = panel.Height;
                if (mouseY < heightSum)
                {
                    rowColumnIndex.Y = i;
                    break;
                }
            }
            //计算列序号
            int widthSum = 0;
            for (int i = 0; i < panel.ColumnCount; i++)
            {
                float currColumnWidth =
                    panel.ColumnStyles[i].SizeType == SizeType.Percent ? panel.Width *0.01F* panel.ColumnStyles[i].Width : panel.ColumnStyles[i].Width;
                if (i < panel.ColumnCount - 1) widthSum += (int)currColumnWidth;
                else if (i == panel.ColumnCount - 1) widthSum = panel.Width;
                if (mouseX < widthSum)
                {
                    rowColumnIndex.X = i;
                    break;
                }
            }
            return rowColumnIndex;
        }

        /// <summary>
        /// 下拉框选定值改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxTempletName_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                string templetName = comboBoxTempletName.Text;
                if (!string.IsNullOrEmpty(templetName))
                {
                    //PrintTemplet = PrintTempletSetSingletonV2d0.Instance.GetPrintTemplet(templetName);
                    PrintTemplet = PrintTempletSet.PrintTempletList.FirstOrDefault(x=>x.TempletName== templetName);
                }
                InitPanel();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }


        private void FormPrintTempletControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("确认退出吗?", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                ReleaseCustomResource();
                Dispose();
                this.Close();// Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 释放自定义资源
        /// </summary>
        public void ReleaseCustomResource()
        {
            try
            {
                foreach (var item in PrintTempletRowDisplayList)
                {
                    item.PanelSelectedEvent -= ProcPanelSelectedEvent;
                }
                foreach (var item in PrintTempletElementEditorList)
                {
                    item.DataChangedEvent -= ProcPrintTempletElementEditdorDataChangedEvent;
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 删除模板行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            DeleteItemOfPrintTempletRowList();
        }
        /// <summary>
        /// 删除模板行（取消待删除模板行的事件订阅，然后删除该模板行）
        /// </summary>
        private void DeleteItemOfPrintTempletRowList()
        {
            try
            {
                //取消模板行显示控件的事件订阅
                foreach (var item in PrintTempletRowDisplayList) item.PanelSelectedEvent -= ProcPanelSelectedEvent;
                PrintTemplet.PrintTempletRowList.RemoveAt(CurrRowIndex);
                if (CurrRowIndex > 0) CurrRowIndex--;
                PrintTempletRowDisplayList = GetTempletItemDisplayList(PrintTemplet);
                FillTableLayoutPanel(PrintTempletRowDisplayList);
                AdjustTableLayoutPanelHeight(PrintTempletRowDisplayList);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 取消哦PrinttempletRowDisplayList的事件订阅
        /// </summary>
        private void CancelEventOfPrintTempletRowDisplayList()
        {
            foreach(var item in PrintTempletRowDisplayList)
            { 
                //取消对应控件的事件订阅
                item.PanelSelectedEvent -= ProcPanelSelectedEvent;
            }
        }
        /// <summary>
        /// PrintTempletRowList增加一条记录
        /// </summary>
        private void AddItemOfPrintTempletRowList()
        {
            try
            {
                AreaTypeV2d0 areaType = PrintTempletRowDisplayList[CurrRowIndex].ContentAreaType;
                PrintTempletRowV2d0 newPrintTempletRow = new PrintTempletRowV2d0();
                newPrintTempletRow.AreaType = areaType;
                newPrintTempletRow.Init3Element();
                PrintTemplet.PrintTempletRowList.Insert(CurrRowIndex + 1, newPrintTempletRow);
                CurrRowIndex++;
                //取消模板行显示控件的事件订阅
                foreach (var item in PrintTempletRowDisplayList) item.PanelSelectedEvent -= ProcPanelSelectedEvent;
                PrintTempletRowDisplayList = GetTempletItemDisplayList(PrintTemplet);
                AdjustTableLayoutPanelHeight(PrintTempletRowDisplayList);
                FillTableLayoutPanel(PrintTempletRowDisplayList);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 根据模板填充容器
        /// </summary>
        /// <param name="printTempletItemDisplayList"></param>
        public List<PrintTempletRowDisplay> GetTempletItemDisplayList(PrintTempletV2d0 printTemplet)
        {
            List<PrintTempletRowDisplay> printTempletRowDisplayList = new List<PrintTempletRowDisplay>();
            try
            {
                //重新设置RowIndex
                int index = 0;
                foreach (var item in printTemplet.PrintTempletRowList)
                {
                    item.RowIndex = index;
                    index++;
                }
                int rowIndex = 0;
                foreach (var rowItem in printTemplet.PrintTempletRowList)
                {
                    PrintTempletRowDisplay rowDisplay = new PrintTempletRowDisplay(rowItem);
                    rowDisplay.Index = rowIndex;
                    rowIndex++;
                    rowDisplay.PanelSelectedEvent -= ProcPanelSelectedEvent;
                    rowDisplay.PanelSelectedEvent += ProcPanelSelectedEvent;
                    rowDisplay.IsSelected = false;
                    printTempletRowDisplayList.Add(rowDisplay);
                }
                //初始化选中第一行，并显示第一行包含的元素
                if (printTempletRowDisplayList.Count > 0)
                {
                    printTempletRowDisplayList[CurrRowIndex].IsSelected = true;
                    printTempletRowDisplayList[CurrRowIndex].Refresh();
                    PrintTempletRow = printTemplet.PrintTempletRowList[CurrRowIndex];
                    FillPrintTempletRowToPanelElement(PrintTempletRow);
                    if (PrintTempletRow.TempletElementList.Count < 3) buttonAddElement.Enabled = true;
                    else buttonAddElement.Enabled = false;
                }
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

            return printTempletRowDisplayList;
        }
        /// <summary>
        /// 将模板行显示控件列表填充到TableLayoutPanel中
        /// </summary>
        /// <param name="printTempletRowDisplayList"></param>
        public void FillTableLayoutPanel(List<PrintTempletRowDisplay> printTempletRowDisplayList)
        {
            try
            {
                //是否需要重新排序？？
                var headerDisplayList = printTempletRowDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Header);
                tableLayoutPanelAreaHeader.Controls.Clear();
                tableLayoutPanelAreaHeader.RowStyles.Clear();
                for (int i = 0; i < headerDisplayList.Count; i++)
                {
                    tableLayoutPanelAreaHeader.Controls.Add(headerDisplayList[i], 0, i);
                    tableLayoutPanelAreaHeader.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 100));
                }

                var detailDisplayList = printTempletRowDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Detail);
                tableLayoutPanelAreaDetail.Controls.Clear();
                tableLayoutPanelAreaDetail.RowStyles.Clear();
                for (int i = 0; i < detailDisplayList.Count; i++)
                {
                    tableLayoutPanelAreaDetail.Controls.Add(detailDisplayList[i], 0, i);
                    tableLayoutPanelAreaDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 100));
                }

                var footerDisplayList = printTempletRowDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Footer);
                tableLayoutPanelAreaFooter.Controls.Clear();
                tableLayoutPanelAreaFooter.RowStyles.Clear();
                for (int i = 0; i < footerDisplayList.Count; i++)
                {
                    tableLayoutPanelAreaFooter.Controls.Add(footerDisplayList[i], 0, i);
                    tableLayoutPanelAreaFooter.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize, 100));
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 根据模板项显示对象列表，调整容器高度
        /// </summary>
        /// <param name="printTempletItemDisplayList"></param>
        public void  AdjustTableLayoutPanelHeight(List<PrintTempletRowDisplay> printTempletItemDisplayList)
        {
            try
            {
                int headerHeight = 0;
                int detailHeight = 0;
                int footerHeight = 0;
                int panelHeight = 0;
                var headerList = printTempletItemDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Header);
                foreach (var item in headerList) headerHeight += item.Height + 7;
                var detailList = printTempletItemDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Detail);
                foreach (var item in detailList) detailHeight += item.Height + 7;
                var footerList = printTempletItemDisplayList.FindAll(x => x.ContentAreaType == AreaTypeV2d0.Footer);
                foreach (var item in footerList) footerHeight += item.Height + 7;
                panelHeight = headerHeight + detailHeight + footerHeight;
                tableLayoutPanelAreaHeader.Height = headerHeight;
                tableLayoutPanelAreaDetail.Height = detailHeight;
                tableLayoutPanelAreaFooter.Height = footerHeight;
                tableLayoutPanelPrintTemplet.Height = panelHeight;
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedElementEditor = PrintTempletElementEditorList.FirstOrDefault(x => x.IsSelected == true);
                if (selectedElementEditor != null)
                {
                    PrintTempletRow.TempletElementList.Remove(selectedElementEditor.PrintTempletElement);
                    FillPrintTempletRowToPanelElement(PrintTempletRow);
                    PrintTempletRowDisplayList[CurrRowIndex].Refresh();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                if (PrintTempletRow.TempletElementList.Count < 3)
                {
                    PrintTempletRow.TempletElementList.Add(new PrintTempletElementV2d0());
                    FillPrintTempletRowToPanelElement(PrintTempletRow);
                    PrintTempletRowDisplayList[CurrRowIndex].Refresh();
                }
                else
                {
                    MessageBox.Show("每个模板行最多有三个元素");
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 新增模板行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddRow_Click(object sender, EventArgs e)
        {
            AddItemOfPrintTempletRowList();
        }
        
        /// <summary>
        /// 上移模板行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMoveRowUp_Click(object sender, EventArgs e)
        {
            MoveTempletRowUp();
        }
        /// <summary>
        /// 模板行上移
        /// </summary>
        private void MoveTempletRowUp()
        {
            try
            {
                if ((CurrRowIndex > 0) &&
                    (PrintTemplet.PrintTempletRowList[CurrRowIndex - 1].AreaType != AreaTypeV2d0.Detail) &&
                    (PrintTemplet.PrintTempletRowList[CurrRowIndex].AreaType != AreaTypeV2d0.Detail))
                {
                    PrintTemplet.PrintTempletRowList.Reverse(CurrRowIndex - 1, 2);
                    CurrRowIndex--;
                    PrintTempletRowDisplayList = GetTempletItemDisplayList(PrintTemplet);
                    FillTableLayoutPanel(PrintTempletRowDisplayList);
                    AdjustTableLayoutPanelHeight(PrintTempletRowDisplayList);
                }
                else MessageBox.Show("该行不能上移");
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

        }
        /// <summary>
        /// 下移模板行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMoveRowDown_Click(object sender, EventArgs e)
        {
            MoveTempletRowDown();
        }
        /// <summary>
        /// 下移模板行
        /// </summary>
        private void MoveTempletRowDown()
        {
            try
            {
                if ((CurrRowIndex < PrintTemplet.PrintTempletRowList.Count - 1) &&
                    (PrintTemplet.PrintTempletRowList[CurrRowIndex + 1].AreaType != AreaTypeV2d0.Detail) &&
                    (PrintTemplet.PrintTempletRowList[CurrRowIndex].AreaType != AreaTypeV2d0.Detail))
                {
                    PrintTemplet.PrintTempletRowList.Reverse(CurrRowIndex, 2);
                    CurrRowIndex++;
                    PrintTempletRowDisplayList = GetTempletItemDisplayList(PrintTemplet);
                    FillTableLayoutPanel(PrintTempletRowDisplayList);
                    AdjustTableLayoutPanelHeight(PrintTempletRowDisplayList);
                }
                else MessageBox.Show("该行不能下移");
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }

        private void buttonDeleteCurrentTemplet_Click(object sender, EventArgs e)
        {
            if (comboBoxTempletName.Items.Count > 1)
            {
                string templetName = comboBoxTempletName.Text;
                //var printTempletSet = PrintTempletSetSingletonV2d0.Instance.GetPrintTempletSet();
                var printTempletSet = PrintTempletSet;
                //删除同名模板，再进行添加
                printTempletSet.PrintTempletList.RemoveAll(x => x.TempletName == templetName);
                string currDir = System.IO.Directory.GetCurrentDirectory();
                string filename = currDir + @"\parameter\printTempletSet.xml";
                PrintTempletSetV2d0.SaveToFile(printTempletSet, filename);
                InitComboBoxTempletName();
            }
            else
            {
                MessageBox.Show("模板集文件中仅包含一个模板，不能执行删除");
            }
        }

        private void buttonDeleteElement_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedElementEditor = PrintTempletElementEditorList.FirstOrDefault(x => x.IsSelected == true);
                if (selectedElementEditor != null)
                {
                    PrintTempletRow.TempletElementList.Remove(selectedElementEditor.PrintTempletElement);
                    FillPrintTempletRowToPanelElement(PrintTempletRow);
                    PrintTempletRowDisplayList[CurrRowIndex].Refresh();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }



        private void buttonSave_Click(object sender, EventArgs e)
        {
            SavePrintTempletToFile();
        }

        private void buttonAddElement_Click(object sender, EventArgs e)
        {
            try
            {
                if (PrintTempletRow.TempletElementList.Count < 3)
                {
                    PrintTempletRow.TempletElementList.Add(new PrintTempletElementV2d0());
                    FillPrintTempletRowToPanelElement(PrintTempletRow);
                    PrintTempletRowDisplayList[CurrRowIndex].Refresh();
                }
                else
                {
                    MessageBox.Show("每个模板行最多有三个元素");
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }

        private void buttonDeleteRow_Click(object sender, EventArgs e)
        {
            DeleteItemOfPrintTempletRowList();
        }
        /// <summary>
        /// 上传更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            List<PrintTempletV2d0> listToBeUpload = new List<PrintTempletV2d0>();
            for (int i=0;i< dataGridView_upload.Rows.Count;i++)
            {
                object isCheckedObject = dataGridView_upload.Rows[i].Cells["isChecked"].Value;
                if (Convert.ToBoolean(isCheckedObject)) listToBeUpload.Add((PrintTempletV2d0)printTempletV2d0BindingSource.List[i]);
            }
            //构造一个模板集 用于上传
            PrintTempletSetV2d0 templetSet = new PrintTempletSetV2d0();
            templetSet.PrintTempletList = listToBeUpload;
            UploadPrintTempletSet(templetSet);
        }


        /// <summary>
        /// 下载模板集
        /// </summary>
        /// <returns></returns>
        private PrintTempletSetV2d0 DownloadPrintTempletSet(List<string> templetGuidList=null)
        {
            PrintTempletSetV2d0 templetSet = null;

            List<rms_print_templet_main> templetMainList = JsonConvert.DeserializeObject<List<rms_print_templet_main>>(GetDataSingletonV1d0.Instance.Run("rms_print_templet_main"));
            List<rms_print_templet_detail> templetDetailList = JsonConvert.DeserializeObject<List<rms_print_templet_detail>>(GetDataSingletonV1d0.Instance.Run("rms_print_templet_detail"));
            if (templetGuidList != null)
            {
                var mainList=templetMainList.FindAll(x => templetGuidList.Contains(x.templet_guid));
                var detailList= templetDetailList.FindAll(x => templetGuidList.Contains(x.templet_guid));
                templetSet = PrintTempletSetV2d0.GetPrintTempletSet(mainList, detailList);
            }
            else
            {
                //开始生成printTempletSetV2d0类
                templetSet = PrintTempletSetV2d0.GetPrintTempletSet(templetMainList, templetDetailList);
            }

            return templetSet;
        }
        /// <summary>
        /// 上传模板集
        /// </summary>
        /// <param name="templetSet"></param>
        private void UploadPrintTempletSet(PrintTempletSetV2d0 templetSet)
        {            
            //本地模板文件数据
            List<rms_print_templet_main> templetList = PrintTempletSetV2d0.GetRmsPrintTempletMainList(templetSet);
            // 远程数据表的的模板列表
            List<rms_print_templet_main> remoteTempletList = 
                JsonConvert.DeserializeObject<List<rms_print_templet_main>>(GetDataSingletonV1d0.Instance.Run("rms_print_templet_main"));
            //本地模板数据并未包含id，uid信息，需要更加模板的guid，设置已有记录的id，uid字段
            foreach (var item in templetList)
            {
                var findedItem = remoteTempletList.FirstOrDefault(x => x.templet_guid == item.templet_guid);
                if (findedItem != null)
                {
                    item.uid = findedItem.uid;
                    item.id = findedItem.id;
                }
            }
            var templetMain = templetList[0];

            List<rms_print_templet_detail> templetDetailList = PrintTempletSetV2d0.GetRmsPrintTempletDetailList(templetSet);
            string result0 =
                SetDataNetMasterSlaveSingletonV1d0.Instance.Run<rms_print_templet_main, rms_print_templet_detail>(templetMain, templetDetailList);
            MessageBox.Show("上传模板完成！！！");
        }
        /// <summary>
        /// 下载覆盖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {

                List<string> listToBeDownload = new List<string>();
                for (int i = 0; i < dataGridView_download.Rows.Count; i++)
                {
                    object isCheckedObject = dataGridView_download.Rows[i].Cells["isChecked"].Value;
                    if (Convert.ToBoolean(isCheckedObject)) listToBeDownload.Add(((rms_print_templet_main)(rmsprinttempletmainBindingSource.List[i])).templet_guid);
                }
                //下载覆盖
                PrintTempletSetV2d0 downloadTempletSet = DownloadPrintTempletSet(listToBeDownload);
                // 合并覆盖
                foreach (var templet in downloadTempletSet.PrintTempletList)
                {
                    int findedIndex = PrintTempletSet.PrintTempletList.FindIndex(x => x.TempletGuid == templet.TempletGuid);
                    if (findedIndex >= 0)
                    {
                        PrintTempletSet.PrintTempletList.RemoveAt(findedIndex);
                        PrintTempletSet.PrintTempletList.Add(templet);
                    }
                    else PrintTempletSet.PrintTempletList.Add(templet);
                }
                //初始化模板名称下拉框
                InitComboBoxTempletName();
                //初始化模板
                InitPanel();
                MessageBox.Show("下载覆盖完成！！！请点击保存，将模板保存到本地");
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 选择上传模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click_1(object sender, EventArgs e)
        {
            printTempletV2d0BindingSource.List.Clear();
            PrintTempletSet.PrintTempletList.ForEach(x => printTempletV2d0BindingSource.List.Add(x));
            //添加选择列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.Name = "isChecked";
            checkBoxColumn.HeaderText = "是否上传";
            //checkBoxColumn.DefaultHeaderCellType=
            dataGridView_upload.Columns.Insert(0, checkBoxColumn);

        }

        private void button4_Click(object sender, EventArgs e)
        {
            rmsprinttempletmainBindingSource.List.Clear();
            string resultString = GetDataSingletonV1d0.Instance.Run("rms_print_templet_main");
            List<rms_print_templet_main> remoteTempletMainList= 
                JsonConvert.DeserializeObject<List<rms_print_templet_main>>(GetDataSingletonV1d0.Instance.Run("rms_print_templet_main"));
            remoteTempletMainList.ForEach(x => rmsprinttempletmainBindingSource.List.Add(x));
            //添加选择列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.Name = "isChecked";
            checkBoxColumn.HeaderText = "是否下载";
            //checkBoxColumn.DefaultHeaderCellType=
            dataGridView_download.Columns.Insert(0, checkBoxColumn);
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            rms_printer printer = new rms_printer();
            printer.name1 = "test";
            printer.name2 = "abc";
            printer.printername = "test2";
            printer.shop_id = 1;

            //SetDataNetSingletonV1d0.Instance.Run<rms_printer>(new rms_printer());
            UpdateDataKeyValueDataNetSingletonV1d0.Instance.Run<rms_printer>("name2", "abc", printer);
        }
    }
}
